package com.vmj.instructions.control;

import com.vmj.common.BytesReader;
import com.vmj.instructions.base.BranchInstruction;
import com.vmj.instructions.base.Instruction;
import com.vmj.rtda.Frame;

/**
 * Created by yangshoujun on 2017/9/24 下午5:07.
 */
public class LookupSwitch implements Instruction {

    int defaultOffset;
    int npairs;
    int[] matchOffsets;

    public void fetchOperands(BytesReader reader) {
        reader.skipPadding();
        defaultOffset = reader.readInt();
        npairs = reader.readInt();
        int len = npairs * 2;
        int[] data = new int[len];
        for(int i = 0; i < len;i++) {
            data[i] = reader.readInt();
        }
        matchOffsets = data;
    }

    public void execute(Frame frame) {
        int key = frame.getOperandStack().popInt();
        for(int i = 0; i < npairs * 2; i += 2) {
            if(matchOffsets[i] == key) {
                int offset = matchOffsets[i + 1];
                BranchInstruction.branch(frame, offset);
                return;
            }
        }
        BranchInstruction.branch(frame, defaultOffset);
    }
}
